<template>
  <div style="margin-top: 0;"> <!-- 将这里的margin-top设为0，减少顶部间距 -->
    <div class="toolbar" style="margin-left: 0;"> <!-- 去除左侧间距 -->
      <el-button type="primary" @click="openAddJobDialog">新增岗位</el-button>
    </div>
    <el-table :data="currentPageData" style="width: 98%; margin-left: 0;" border :row-class-name="tableRowClassName"> <!-- 去除表格左侧间距 -->
      <el-table-column prop="jobId" label="岗位 ID" width="100" align="center"></el-table-column> <!-- 微调列宽 -->
      <el-table-column prop="entName" label="公司名称" width="100" align="center"></el-table-column> <!-- 微调列宽 -->
      <el-table-column prop="jobTitle" label="岗位名称" width="100" align="center"></el-table-column> <!-- 微调列宽 -->
      <el-table-column label="岗位描述"  align="center"> <!-- 微调列宽 -->
        <template #default="{ row }">
          <span @click="openFullDescriptionDialog(row.jobRequire)" style="cursor: pointer; color: #409EFF;">
            {{ row.jobRequire.length > 20? row.jobRequire.slice(0, 20) + '...' : row.jobRequire }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="jobminsalary" label="最低薪资" width="100" align="center"></el-table-column>
      <el-table-column prop="jobmaxsalary" label="最高薪资" width="100" align="center"></el-table-column>
      <el-table-column label="更新" width="100" align="center"> <!-- 微调列宽 -->
        <template #default="{ row }">
          <el-button type="primary" @click="openUpdateDialog(row)">更新</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center"> <!-- 微调列宽 -->
        <template #default="{ row }">
          <el-button type="danger" @click="deleteJob(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin: 0 0 10px 0; "
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="totalRecords"
      layout="total, prev, pager, next, jumper"
    />
    <el-dialog v-model="dialogVisible" title="新增岗位信息" width="60%">
      <el-form :model="newJob" label-width="120px">
        <el-form-item label="公司名称" prop="entName">
          <el-select v-model="newJob.entName" @change="selectEnterprise">
            <el-option
              v-for="enterprise in enterprises"
              :key="enterprise.entId"
              :label="enterprise.entName"
              :value="enterprise.entName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="企业 ID" prop="entId">
          <el-input v-model="newJob.entId" readonly />
        </el-form-item>
        <el-form-item label="岗位名称" prop="jobTitle">
          <el-input v-model="newJob.jobTitle" />
        </el-form-item>
        <el-form-item label="岗位描述" prop="jobRequire">
          <el-input v-model="newJob.jobRequire" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="最低薪资" prop="jobminsalary">
          <el-input v-model.number="newJob.jobminsalary" />
        </el-form-item>
        <el-form-item label="最高薪资" prop="jobmaxsalary">
          <el-input v-model.number="newJob.jobmaxsalary" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addJob">新增</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="updateDialogVisible" title="更新岗位信息" width="60%">
      <el-form :model="updatedJob" label-width="120px">
        <el-form-item label="公司名称" prop="entName">
          <el-input v-model="updatedJob.entName" />
        </el-form-item>
        <el-form-item label="企业 ID" prop="entId">
          <el-input v-model="updatedJob.entId" />
        </el-form-item>
        <el-form-item label="岗位名称" prop="jobTitle">
          <el-input v-model="updatedJob.jobTitle" />
        </el-form-item>
        <el-form-item label="岗位描述" prop="jobRequire">
          <el-input v-model="updatedJob.jobRequire" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="最低薪资" prop="jobminsalary">
          <el-input v-model.number="updatedJob.jobminsalary" />
        </el-form-item>
        <el-form-item label="最高薪资" prop="jobmaxsalary">
          <el-input v-model.number="updatedJob.jobmaxsalary" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateJob">更新</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="fullDescriptionDialogVisible" title="岗位描述详情" width="60%">
      <el-form :model="fullDescriptionForm" label-width="120px">
        <el-form-item label="岗位描述" prop="description">
          <el-input
            v-model="fullDescriptionForm.description"
            type="textarea"
            :rows="15"
            readonly
            class="description-textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="fullDescriptionDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    <div v-if="isLoading" class="loading">加载中...</div>
  </div>
</template>

<script>
// 这里代码保持不变，不修改功能相关逻辑
import axios from 'axios';
axios.defaults.headers.post['Content-Type'] = 'application/json';
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import {
  getJobListApi,
  addJobApi,
  jobDeleteApi,
  jobUpdateApi,
  getEnterpriseListApi
} from '@/api/ent-api';

export default {
  components: { Plus },
  setup() {
    // 搜索查询条件
    const searchQuery = ref('');
    // 新增岗位对话框可见性
    const dialogVisible = ref(false);
    // 更新岗位对话框可见性
    const updateDialogVisible = ref(false);
    // 岗位描述详情对话框可见性
    const fullDescriptionDialogVisible = ref(false);
    // 当前页码
    const currentPage = ref(1);
    // 每页数量
    const pageSize = ref(10);
    // 总记录数
    const totalRecords = ref(0);
    // 所有岗位数据
    const allJobs = ref([]);
    // 加载状态
    const isLoading = ref(false);
    // 企业列表数据
    const enterprises = ref([]);

    // 新增岗位表单数据
    const newJob = reactive({
      entName: '',
      jobTitle: '',
      jobRequire: '',
      jobminsalary: null,
      jobmaxsalary: null,
      entId: null
    });

    // 更新岗位表单数据
    const updatedJob = reactive({
      entName: '',
      jobTitle: '',
      jobRequire: '',
      jobminsalary: null,
      jobmaxsalary: null,
      entId: null,
      jobId: null
    });

    // 岗位描述详情表单数据
    const fullDescriptionForm = reactive({
      description: ''
    });

    // 当前页数据计算属性
    const currentPageData = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return allJobs.value.slice(start, end);
    });

    // 页面挂载时获取岗位列表和企业列表
    onMounted(async () => {
      await searchJobs();
      await getEnterpriseList();
    });

    // 搜索岗位列表
    const searchJobs = async () => {
  isLoading.value = true;
  try {
    const { records, total } = await getJobListApi({
      page: currentPage.value,
      size: pageSize.value,
      name: searchQuery.value
    });
    console.log('接口返回的原始数据:', { records, total });
    if (Array.isArray(records)) {
      const newData = records.map(item => ({
        
       ...item,
        jobminsalary: item.jobminsalary? `${item.jobminsalary} 元` : '',
        jobmaxsalary: item.jobmaxsalary? `${item.jobmaxsalary} 元` : ''
      }));
      const startIndex = (currentPage.value - 1) * pageSize.value;
      allJobs.value.splice(startIndex, pageSize.value, ...newData);
      totalRecords.value = total || 0;
    } else {
      ElMessage.error('接口返回的数据格式不正确，请联系管理员');
    }
  } catch (error) {
    ElMessage.error('搜索失败，请稍后再试');
  } finally {
    isLoading.value = false;
  }
};

    // 获取企业列表
    const getEnterpriseList = async () => {
      try {
        const response = await getEnterpriseListApi();
        if (response && Array.isArray(response.data)) {
          enterprises.value = response.data;
        } else {
          ElMessage.error('获取企业列表失败，请联系管理员');
        }
      } catch (error) {
        ElMessage.error('获取企业列表失败，请稍后再试');
      }
    };

    // 打开新增岗位对话框
    const openAddJobDialog = () => {
      dialogVisible.value = true;
      Object.assign(newJob, {
        entName: '',
        jobTitle: '',
        jobRequire: '',
        jobminsalary: null,
        jobmaxsalary: null,
        entId: null
      });
    };

    // 选择企业时更新企业 ID
    const selectEnterprise = () => {
      const selectedEnterprise = enterprises.value.find(
        enterprise => enterprise.entName === newJob.entName
      );
      newJob.entId = selectedEnterprise?.entId || null;
    };

    // 新增岗位
    const addJob = async () => {
      const requiredFields = ['entName', 'jobTitle', 'jobRequire', 'jobminsalary', 'jobmaxsalary', 'entId'];
      const missingFields = requiredFields.filter(field =>!newJob[field]);
      if (missingFields.length > 0) {
        const fieldNames = {
          entName: '公司名称',
          jobTitle: '岗位名称',
          jobRequire: '岗位描述',
          jobminsalary: '最低薪资',
          jobmaxsalary: '最高薪资',
          entId: '企业 ID'
        };
        const missingFieldNames = missingFields.map(field => fieldNames[field]).join(', ');
        ElMessage.error(`请填写以下必填项: ${missingFieldNames}`);
        return;
      }
      if (newJob.jobminsalary > newJob.jobmaxsalary) {
        ElMessage.error('最低薪资不能大于最高薪资，请重新输入');
        return;
      }
      try {
        await addJobApi(newJob);
        await searchJobs();
        totalRecords.value = (await getJobListApi({
          page: currentPage.value,
          size: pageSize.value,
          name: searchQuery.value
        })).total || 0;
        dialogVisible.value = false;
        ElMessage.success('新增岗位成功');
      } catch (error) {
        ElMessage.error('新增岗位失败，请稍后再试');
      }
    };

    // 删除岗位
    const deleteJob = async (row) => {
      const jobId = row.jobId;
      if (!jobId) {
        ElMessage.error('岗位删除失败,job_id 值未定义');
        return;
      }
      if (confirm('确定要删除该岗位吗？')) {
        try {
          const response = await jobDeleteApi(jobId);
          if (response.data) {
            allJobs.value = allJobs.value.filter(item => item.jobId!== jobId);
            totalRecords.value = (await getJobListApi({
              page: currentPage.value,
              size: pageSize.value,
              name: searchQuery.value
            })).total || 0;
            ElMessage.success('岗位删除成功');
          } else {
            ElMessage.error(response.msg || '岗位删除失败');
          }
        } catch (error) {
          ElMessage.error('岗位删除失败，请稍后再试');
        }
      }
    };

    // 打开更新岗位对话框
    const openUpdateDialog = (row) => {
      updateDialogVisible.value = true;
      Object.assign(updatedJob, row);
    };

    // 更新岗位
    const updateJob = async () => {
      const requiredFields = ['entName', 'jobTitle', 'jobRequire', 'jobminsalary', 'jobmaxsalary', 'entId', 'jobId'];
      const missingFields = requiredFields.filter(field =>!updatedJob[field]);
      if (missingFields.length > 0) {
        const fieldNames = {
          entName: '公司名称',
          jobTitle: '岗位名称',
          jobRequire: '岗位描述',
          jobminsalary: '最低薪资',
          jobmaxsalary: '最高薪资',
          entId: '企业 ID',
          jobId: '岗位 ID'
        };
        const missingFieldNames = missingFields.map(field => fieldNames[field]).join(', ');
        ElMessage.error(`请填写以下必填项: ${missingFieldNames}`);
        return;
      }
      if (updatedJob.jobminsalary > updatedJob.jobmaxsalary) {
        ElMessage.error('最低薪资不能大于最高薪资，请重新输入');
        return;
      }
      try {
        await jobUpdateApi(updatedJob);
        await searchJobs();
        updateDialogVisible.value = false;
        ElMessage.success('岗位更新成功');
      } catch (error) {
        ElMessage.error('岗位更新失败，请稍后再试');
      }
    };

    // 打开岗位描述详情对话框
    const openFullDescriptionDialog = (description) => {
      fullDescriptionDialogVisible.value = true;
      fullDescriptionForm.description = String(description || '无描述内容');
    };

    // 分页切换时重新搜索岗位
    const handleCurrentChange = (page) => {
      currentPage.value = page;
      searchJobs();
    };
    const tableRowClassName = (row, rowIndex) => {
      return {
        'success-row': row.rowIndex%2 === 0
      };
    };

    return {
      searchQuery,
      dialogVisible,
      updateDialogVisible,
      fullDescriptionDialogVisible,
      newJob,
      updatedJob,
      fullDescriptionForm,
      allJobs,
      currentPageData,
      currentPage,
      pageSize,
      totalRecords,
      isLoading,
      enterprises,
      openAddJobDialog,
      addJob,
      deleteJob,
      openUpdateDialog,
      updateJob,
      openFullDescriptionDialog,
      handleCurrentChange,
      selectEnterprise,
      tableRowClassName
    };
  }
};
</script>

<style scoped>
.toolbar {
  margin-bottom: 10px; 
}

.loading {
  text-align: center;
  margin-top: 10px; 
  color: #999;
}

.description-textarea {
  font-family: inherit;
  line-height: 1.5;
}

:deep(.description-textarea .el-textarea__inner) {
  color: #333;
  background-color: #f8f8f8;
  min-height: 300px;
  white-space: pre-wrap;
  resize: none;
  font-size: 14px;
  padding: 12px;
  border: 1px solid #e6e6e6;
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>